package com.huan.springcloud;


import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Hello world!
 *
 */
public class Consumer
{
    public static void main( String[] args ) throws Exception {
//        boolean activMercRelationTopic = RocketMQUtil.createTopic("paidmq-namesvr01.yspos-fat.com", "activMercRelationTopic");
//        boolean activMercRelationTopic = RocketMQUtil.createTopic("10.213.32.177:9876", "activMercRelationTopic");
//        boolean topic = RocketMQUtil.createTopic("10.213.32.177:9876;10.213.32.178:9876", "DefaultCluster", "activMercRelationTopic");
//        System.out.println(topic);

       DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("MarketingActivMercRelationGroup");
//       consumer.setNamesrvAddr("10.213.32.41:9876;10.213.32.42:9876");
//       consumer.setNamesrvAddr("10.213.32.177:9876;10.213.32.178:9876");
       consumer.setNamesrvAddr("192.168.56.100:9876");
       /**
                     * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
                     * 如果非第一次启动，那么按照上次消费的位置继续消费
                     */
       consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
       consumer.setConsumeMessageBatchMaxSize(10);

       consumer.subscribe("MarketingActivMercRelationTopic", "*");

       consumer.registerMessageListener(new MessageListenerOrderly() {

           Random random = new Random();

           @Override
           public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
               context.setAutoCommit(true);
               System.out.println("数量="+msgs.size());
               for (MessageExt msg : msgs) {
                   // 可以看到每个queue有唯一的consume线程来消费, 订单对每个queue(分区)有序
                   System.out.println(msg);
                   System.out.println("consumeThread=" + Thread.currentThread().getName() + "queueId=" + msg.getQueueId() + ", content:" + new String(msg.getBody()));
               }

               try {
                   //模拟业务逻辑处理中...
                   TimeUnit.SECONDS.sleep(random.nextInt(10));
               } catch (Exception e) {
                   e.printStackTrace();
               }
               return ConsumeOrderlyStatus.SUCCESS;
           }
       });

       consumer.start();

       System.out.println("Consumer Started.");
    }
}
